package uit.nfcmenu.waiter.activities;

import java.util.ArrayList;
import java.util.Hashtable;

import uit.nfcmenu.waiter.controllers.DatabaseManagerChef;
import uit.nfcmenu.waiter.controllers.ListOrderStatusModelsAdapter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;

import uit.nfcmenu.models.IDataChangeHandler;
import uit.nfcmenu.models.OrderChef;
import uit.nfcmenu.utils.CommConstant.OrderStates;
import uit.nfcmenu.waiter.R;

public class OrderListActivity extends Activity implements OnClickListener,
		IDataChangeHandler {
	DatabaseManagerChef mDBManager;
	ListView lv;
	getdatainbackground thread;
	boolean flag;
	// ProgressDialog pro;
	Context parrent = this;
	String tag = OrderListActivity.class.getSimpleName();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.order_list);
//		CommonContrans.orderListActivity = this;
		lv = (ListView) findViewById(R.id.lvOrder);
		Button btnLogout = (Button) findViewById(R.id.btnLogout);
//		Button btnCookedList = (Button) findViewById(R.id.btnCookedList);
		btnLogout.setOnClickListener(OrderListActivity.this);
//		btnCookedList.setOnClickListener(OrderListActivity.this);
		mDBManager = DatabaseManagerChef.getInstance(OrderListActivity.this);

		mDBManager.getAllItem();
		mDBManager.getOrdersInDB();

		ArrayList<OrderChef> items = mDBManager.getOrdersInDB();
		ArrayList<OrderChef> mArrItemModelsList = new ArrayList<OrderChef>();
		for (int i = 0; i < items.size(); i++) {
			OrderChef model = new OrderChef(items.get(i));
			if (!(OrderStates.valueOf(model.getStatus()) == OrderStates.COOKED)
					&& !(OrderStates.valueOf(model.getStatus()) == OrderStates.DENY)
					&& !(OrderStates.valueOf(model.getStatus()) == OrderStates.DONE)
					&& !(OrderStates.valueOf(model.getStatus()) == OrderStates.SERVED)) {
				mArrItemModelsList.add(model);
			}
		}
		lv.setAdapter(new ListOrderStatusModelsAdapter(OrderListActivity.this,
				mArrItemModelsList, OrderListActivity.this));

		// thread = new getdatainbackground();
		// thread.start();
		flag = false;
		new BackgroundAsyncTask().execute();
	}

	public void onClick(View v) {
		Intent i;
		switch (v.getId()) {
//		case R.id.btnCookedList:
//			i = new Intent(this, CookedListActivity.class);
//			startActivity(i);
//
//			break;
		case R.id.btnLogout:
			i = new Intent(this, LoginActivity.class);

//			CommonContrans.orderListActivity = null;
			finish();
			break;
		}

	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		thread.isPlay = false;
		flag = false;
		if (mDBManager != null) {
			mDBManager.stop();
		}
		super.onPause();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		Log.i(tag, "onResume");
//		CommonContrans.orderListActivity = this;
		if (mDBManager == null) {
			mDBManager = DatabaseManagerChef
					.getInstance(OrderListActivity.this);
			
		}

		if (!flag) {
			thread = new getdatainbackground();
			thread.start();
			
			mDBManager.start();
			flag=true;
		}
		super.onResume();
	}

	class getdatainbackground extends Thread {
		public boolean isPlay;
		public long nextTimeCheck;

		public getdatainbackground() {
			isPlay = true;
			nextTimeCheck = System.currentTimeMillis() + 10000;

		}

		public void run() {
			while (isPlay) {
				if (nextTimeCheck <= System.currentTimeMillis()) {
					nextTimeCheck = System.currentTimeMillis() + 10000;
					ListOrderStatusModelsAdapter adapter = (ListOrderStatusModelsAdapter) lv
							.getAdapter();
					if (adapter == null) {
						continue;
					}
					ArrayList<OrderChef> array = adapter.getItemModels();
					for (int i = 0; i < array.size(); i++) {
						if (array.get(i).getStatus().equals("COOKING")) {
							array.get(i).setTime(array.get(i).getTime() + 10);
						}
					}
					Log.i(tag, "post");
					mHandler.sendEmptyMessage(0);
				}
			}
		}
	}

	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			if (msg.what == 1) {
				Log.e(tag, "update");
				ArrayList<OrderChef> items;
				items = mDBManager.getOrdersInDB();
				Hashtable<Integer, Integer>hash=new Hashtable<Integer, Integer>();
				ListOrderStatusModelsAdapter adapter = (ListOrderStatusModelsAdapter) lv
						.getAdapter();

				try {
					ArrayList<OrderChef> mArray = adapter.getItemModels();
					for(int i=0;i<mArray.size();i++){
						if(mArray.get(i).getStatus().equals("COOKING")){
							hash.put(mArray.get(i).getOrderID(), mArray.get(i).getTime());
						}
					}
					items = mDBManager.getOrdersInDB();
					ArrayList<OrderChef> mArrItemModelsList = new ArrayList<OrderChef>();
					for (int i = 0; i < items.size(); i++) {
						OrderChef model = new OrderChef(items.get(i));
						if (!(OrderStates.valueOf(model.getStatus()) == OrderStates.COOKED)
								&& !(OrderStates.valueOf(model.getStatus()) == OrderStates.DENY)
								&& !(OrderStates.valueOf(model.getStatus()) == OrderStates.DONE)
								&& !(OrderStates.valueOf(model.getStatus()) == OrderStates.SERVED)) {
							mArrItemModelsList.add(model);
							if(model.getStatus().equals("COOKING")){
								model.setTime(hash.get(model.getOrderID()));
							}
						}
					}
					lv.setAdapter(new ListOrderStatusModelsAdapter(OrderListActivity.this,
							mArrItemModelsList, OrderListActivity.this));
					Log.e(tag, "end update");
					
//					for (int i = 0; i < mArray.size(); i++) {
//						for (int j = 0; j < items.size(); i++) {
//							if (items.get(j).getOrderID() == mArray.get(i)
//									.getOrderID()) {
//								mArray.get(i).update(items.get(j));
//								items.remove(j);
//								break;
//							}
//						}
//					}
//					for (int i = 0; i < items.size(); i++) {
//						OrderChef model = new OrderChef(items.get(i));
//						if (!(OrderStates.valueOf(model.getStatus()) == OrderStates.COOKED)
//								&& !(OrderStates.valueOf(model.getStatus()) == OrderStates.DENY)
//								&& !(OrderStates.valueOf(model.getStatus()) == OrderStates.DONE)
//								&& !(OrderStates.valueOf(model.getStatus()) == OrderStates.SERVED)) {
//							mArray.add(model);
//						}
//					}
					// adapter.setItemModels(arrItemModels);
//					adapter.setItemModels(mArray);
//					adapter.notifyDataSetChanged();
				} catch (Exception e) {
					return;
				}
			} else if (msg.what == 0) {
				ListOrderStatusModelsAdapter adapter = (ListOrderStatusModelsAdapter) lv
						.getAdapter();
				adapter.notifyDataSetChanged();
			}
		}
	};

	public void onDataChanged() {
		// TODO Auto-generated method stub
		Log.i(OrderListActivity.class.getSimpleName(), "onDataChanged()");
		mHandler.sendEmptyMessage(1);

	}

	public Context getContext() {
		// TODO Auto-generated method stub
		return getApplicationContext();
	}

	public class BackgroundAsyncTask extends AsyncTask<Void, Integer, Void> {

		@Override
		protected void onPreExecute() {

			// pro = new ProgressDialog(parrent).show(parrent, "Waiting...",
			// null);

		}

		@Override
		protected Void doInBackground(Void... params) {

			// TODO Auto-generated method stub\

			try {

				try {
					Log.i(tag, "get all");
					mDBManager.getAllFoodsAndDrinksFromServer();
					Log.i(tag, "end get all");

				} catch (Exception e) {

				}

				publishProgress(1);
			} catch (Exception e) {
				// TODO Auto-generated catch block

				publishProgress(3);

			}
			return null;
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			// TODO Auto-generated method stub
			int a = values[0];
			if (a == 1) {

				mDBManager.getAllItem();

				mHandler.sendEmptyMessage(1);
				Log.i(tag, "start database manager");
				mDBManager.start();
			
				// pro.dismiss();
			}
			
			// pro.dismiss();
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			// pro.dismiss();
			
		}
	}
}
